package leetcode.p1737;

/**
 * @author: trtan
 * @create: 2021-04-09 16:25
 * @description:
 **/
public class ChangeMinimumCount {
    public static void main(String[] args) {
        String a = "otpaynexxlngyrdmand";
        String b = "twtyifiiundfejxfktclktjnqrmycnqmxhxfitnlasyuwotjguerenjjnpkaajsnnraopdnambfccwthppimijghg";


        System.out.println(new ChangeMinimumCount().minCharacters(a, b));
    }

    public int minCharacters(String a, String b) {
        int[] countA = new int[26];
        int[] countB = new int[26];
        for (int i = 0; i < a.length(); i++) {
            countA[a.charAt(i) - 'a']++;
        }
        for (int i = 0; i < b.length(); i++) {
            countB[b.charAt(i) - 'a']++;
        }
        for (int i = 0; i < countA.length; i++) {
            System.out.println(countA[i] + ", " + countB[i]);
        }
        int result = a.length() + b.length();
        for (int i = 0; i < countA.length; i++) {
            //把a中字符全部改为小于b中字符的最少次数
            int sumALessThanB = 0;
            //把b中字符全部改为小于a中字符的最少次数
            int sumBLessThanA = 0;
            //把a、b中字符改为全部相等的最少次数
            int sumEquals = a.length() + b.length();
            if (i != 0 && i != 25) {
                for (int j = 0; j < i; j++) {
                    //b中比'a'+i小的全部改到'a'+i --求sumALessThanB
                    sumALessThanB += countB[j];
                    //a中比'a'+i小的全部改到'a'+i --求sumBLessThanA
                    sumBLessThanA += countA[j];
                }

                for (int j = i; j < countA.length; j++) {
                    //a中比'a'+i大于等于的全部改到'a'+i-1 --求sumALessThanB
                    sumALessThanB += countA[j];
                    //b中比'a'+i大于等于的全部改到'a'+i-1 --求sumBLessThanA
                    sumBLessThanA += countB[j];
                }
            } else if (i == 0) {
                //特殊情况，把a中全部改成'a'+i，b中的'a'+i改为'a'+i+1
                sumALessThanB = a.length() - countA[i] + countB[i];
                sumBLessThanA = b.length() - countB[i] + countA[i];
            } else if (i == 25) {
                //特殊情况，把b中全部改成'a'+i，a中的'a'+i改为'a'+i-1
                sumALessThanB = b.length() - countB[i] + countA[i];
                sumBLessThanA = a.length() - countA[i] + countB[i];
            }

            //去除a中等于'a'+i的字符 --求sumEquals
            sumEquals -= countA[i];
            //去除b中等于'a'+i的字符 --求sumEquals
            sumEquals -= countB[i];
            System.out.println(i + ": " + result + ", " + sumALessThanB + ", " + sumBLessThanA + ", " + sumEquals);
            result = Math.min(result, Math.min(sumALessThanB, Math.min(sumBLessThanA, sumEquals)));
        }
        return  result;
    }
}
